package classroom;

import java.util.*;

public class Classroom {
    // 人不能有重复，所以使用set。重写了people类的equals 和 hashcode函数，集合才可以更合理地查重
    private Set<People> peoples = new HashSet<>();
    private String name;
    // 记录题目到答案的映射。存储<题目，答案>键值对。
    private static Map<String, String> question2answer = new HashMap<>();

    public Classroom(String name) {
        this.name = name;
        //添加默认题库
        question2answer.put("1+1=?", "2");
        question2answer.put("杨晨学姐美不美?", "美！");
    }

    public String getName() {
        return name;
    }

    /**
     * 添加问题
     * @param question 问题
     * @param answer 答案
     * @return 教室
     */
    public Classroom addQA(String question,String answer){
        question2answer.put(question,answer);
        return this;
    }

    /**
     * 给教室添加人
     * @param people 人
     * @return 教室
     */
    public Classroom addPeople(People people) {
        peoples.add(people);
        return this;
    }

    public void addPeople(List<People> peoples) {
        this.peoples.addAll(peoples);
    }

    public void addPeople(People... peoples) {
        this.peoples.addAll(Arrays.asList(peoples));
    }

    /**
     * 提供答案查询功能
     * @param question
     * @return
     */
    public static String getAnswer(String question) {
        return question2answer.get(question);
    }

    /**
     * 开始讨论
     */
    public void discuss() {
        int askIndex, answerIndex, questionIndex;
        // 将人和问题转成数组
        People[] peopleArray = new People[peoples.size()];
        String[] questionArray = new String[question2answer.keySet().size()];
        question2answer.keySet().toArray(questionArray);
        peoples.toArray(peopleArray);
        for (int k = 0; k < 5; k++) {
            //通过Math.random取随机数得到随机的索引值。
            askIndex = (int) (Math.random() * peopleArray.length);
            answerIndex = (int) (Math.random() * peopleArray.length);
            while (answerIndex == askIndex) {
                answerIndex = (int) (Math.random() * peopleArray.length);
            }
            questionIndex = (int) (Math.random() * questionArray.length);
            //随机选择一个人随机问另一个人随机一个问题
            peopleArray[askIndex].askQuestion(peopleArray[answerIndex], questionArray[questionIndex]);
        }
    }
}
